<?php

class UsersController extends Controller {
    var $name = 'Users';
    var $uses = array('Users', 'Groups', 'Posts');
    var $components = array('page', 'attachment', 'json', 'user');

    function index() {
        $this->action = 'users';
        $this->users();
    }

    function users($page = null) {
        $page = intval($page);
        $users = $this->__get_users_list($page);
        $this->set('users', $users->users);
        $this->set('pagelink', $users->pagelink);
        $this->set('page', $page);
        $group = $this->Groups->find("is_anonymous!='1'", array('id'));
        $this->set('has_group', $group);
    }

    function user_edit($user_id = null) {
        if (empty($user_id)) {
            $this->error_404();
        }
        $user = current_user();
        if ($user_id == $user->id) {
            $this->redirect('/profile');
            exit();
        }
        if (!empty($this->data)) {
            if (!empty($this->data['Users']['password_alpha']) && $this->data['Users']['password_alpha'] == $this->data['Users']['password_beta']) {
                $this->data['Users']['password'] = md5($this->data['Users']['password_alpha']);
            }
            $this->data['Users']['id'] = $user_id;
            $this->Users->save($this->data);
            $this->redirect('/users/users/edit_done');
            exit();
        }
        $this->Users->id = $user_id;
        $userinfo = $this->Users->read();
        $this->set('user_id', $user_id);
        $this->set('username', $userinfo->username);
        $this->data['Users']['group_id'] = $userinfo->group_id;
        $this->data['Users']['nickname'] = $userinfo->nickname;
        $this->data['Users']['email'] = $userinfo->email;
        $this->data['Users']['url'] = $userinfo->url;
        $this->data['Users']['tell'] = $userinfo->tell;
        $this->data['Users']['aim'] = $userinfo->aim;
        $this->data['Users']['yim'] = $userinfo->yim;
        $this->data['Users']['jabber'] = $userinfo->jabber;
        $this->action = 'user_create';
        $this->set('title', __('Edit user'));
        $this->set('submit_value', __('Update user'));
        $this->set('groups', $this->__get_group_data());

        $status = $this->__get_user_status($userinfo->status);
        $this->set('status', $status);
    }

    function user_create($status = null) {
        if (!empty($this->data)) {
            if (!empty($this->data['Users']['username'])) {
                if (!empty($this->data['Users']['password_alpha'])) {
                    if ($this->data['Users']['password_alpha'] == $this->data['Users']['password_beta']) {
                        $this->data['Users']['password'] = md5($this->data['Users']['password_alpha']);
                        $user_id = $this->Users->find('username="' . $this->data['Users']['username'] . '"', array('id'));
                        if (empty($user_id)) {
                            $this->data['Users']['status'] = 1;
                            $this->data['Users']['date_joined'] = time();
                            $this->Users->save($this->data);
                            $this->data = null;
                            $this->redirect('/users/user_create/add_done');
                        } else {
                            $this->header_notice = __('This username is already registered, please choose another one.');
                        }
                    } else {
                        $this->header_notice = __('Please type the same password in the two password fields.');
                    }
                } else {
                    $this->header_notice = __('Please enter your password twice.');
                }
            } else {
                $this->header_notice = __('Please enter the username.');
            }
        }
        if ($status == 'add_done') {
            $this->header_notice = __('Add user done.');
        }
        $this->set('groups', $this->__get_group_data());
        $this->set('title', __('Create a new user'));
        $this->set('submit_value', __('Create user'));
        $this->set('user_id', null);
    }

    function __get_users_list($page) {
        $perpage = 30;
        $page = intval($page);
        $user = current_user();
        $user_count = $this->Users->get_count("id!='$user->id'", 'id');
        $totalpages = ceil($user_count/$perpage);
        if ($page < 1) {
            $page = 1;
        } else if ($page > $totalpages) {
            $page = $totalpages;
        }
        $info = null;
        $start = ($page -1) * $perpage;

        $info->users = $this->Users->find_all("id!='$user->id'", array('id', 'username', 'is_superuser', 'group_id', 'last_login', 'status'), "ORDER BY id DESC LIMIT $start,$perpage");
        $info->pagelink = get_pagelink(Router::get_url() . sprintf('/%s/users/', ARLICLE_ADMIN), $page, $user_count, $perpage, $totalpages);
        return $info;
    }

    function __get_group_data() {
        $groups = $this->Groups->find_all("id!='1'", array('id', 'title'));
        $group_data = array();
        if (!empty($groups)) {
            foreach($groups as $group) {
                $group_data[$group->id] = $group->title;
            }
        }
        return $group_data;
    }

    function ajax_delete_users($page, $action, $ids) {
        $this->layout = null;
        $ids = trim($ids, '|');
        $ids = explode('|', $ids);
        $message = null;
        $user = current_user();
        foreach($ids as $id) {
            if ($id == $user->id || $id == 1) {
                continue;
            }
            if ($action == 1) {
                $this->Users->id = $id;
                $this->Users->save_field('status', 2);
                $message['message'] = __('Inactive users done.');
            } else if ($action == 2) {
                $this->Users->del($id);
                $message['message'] = __('Delete users done.');
            } else if ($action == 3) {
                $this->Users->del($id);
                $posts = $this->Posts->find_all("poster_id='$id'", array('id'));
                if (!empty($posts)) {
                    foreach($posts as $post_id) {
                        delete_attachments($post_id);
                    }
                }
                $this->Posts->del_all("poster_id='$id'");
                $message['message'] = __('Delete users and his posts done.');
            }
        }

        $usersinfo = $this->__get_users_list($page);
        $message['table_list'] = '
        <table>
      <tr>
        <th colspan="3" class="tablebar"> <input value="' . __('Delete users') . '" type="button" id="deleteT" onclick="delete_users();">
        </th>
        <td colspan="2" class="tablebar" align="right">' . $usersinfo->pagelink . '</td>
      </tr>

      <tr>
        <th><input value="" type="checkbox" name="select_all" id="select_all" class="chose_user" onclick="mod_allcheckbox_status2(\'user_id[]\', this.checked);"></th>
        <th>' . __('Username') . '</th>
        <th>' . __('Group') . '</th>
        <th>' . __('Last signed in') . '</th>
        <th>' . __('Status') . '</th>
      </tr>';
        if (!empty($usersinfo->users)) {
            foreach($usersinfo->users as $user) {
                $status = null;
                if ($user->status == 1) {
                    $status = __('Active');
                } else if ($user->status == 2) {
                    $status = __('Inactive');
                } else if ($user->status == 0) {
                    $status = __('Deleted');
                }
                $group_title = get_group_title($user->group_id);
                $message['table_list'] .= '<tr class=""><td>';
                if ($user->id != 1) {
                    $message['table_list'] .= '<input value="' . $user->id . '" type="checkbox" name="user_id[]" class="chose_user" onclick="change_allcheckbox_status(\'user_id[]\', \'select_all\');" />';
                }
                $message['table_list'] .= '
        </td>
        <td>
        <a href="' . Router::get_url() . sprintf('/%s/users/', ARLICLE_ADMIN) . 'user_edit/' . $user->id . '">' . $user->username . '</a>
         </td>

        <td>' . $group_title . '</td>
        <td>' . (!empty($user->last_login) ? date('Y-m-d H:i', $user->last_login) : __('Never logged in')) . '</td>
        <td>' . $status . '</td>
      </tr>';
            }
        }
        $message['table_list'] .= '<tr>
        <td colspan="3" class="tablebar"> <input value="' . __('Delete users') . '" type="button" id="deleteT" onclick="delete_users();">
        </td>
        <td colspan="2" class="tablebar" align="right">' . $usersinfo->pagelink . '</td>
      </tr>
    </table>';
        $json = new Services_JSON();
        $output = $json->encode($message);
        echo $output;
    }

    function ajax_change_user_status($user_id = null) {
        if (empty($user_id) || ($user_id == 1)) {
            $this->error_404();
        }
        $this->layout = null;
        $this->Users->id = $user_id;
        $user = $this->Users->read('status');
        $status = null;
        if ($user->status == 1) {
            $status = 2;
        } else if ($user->status == 2) {
            $status = 1;
        } else {
            $status = 0;
        }
        $status_word = $this->__get_user_status($status);
        $this->Users->save_field('status', $status);
        echo $status_word;
    }
    
    function __get_user_status($status_code) {
        if ($status_code == 2) {
            $status = __('Inactive');
        } else if ($status_code == 1) {
            $status = __('Active');
        }
        return $status;
    }
}

?>
